package com.atguigu.ssyx.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.ssyx.client.order.OrderFeignClient;
import com.atguigu.ssyx.common.constant.MqConst;
import com.atguigu.ssyx.common.exception.SsyxException;
import com.atguigu.ssyx.common.result.ResultCodeEnum;
import com.atguigu.ssyx.common.service.RabbitService;
import com.atguigu.ssyx.enums.PaymentStatus;
import com.atguigu.ssyx.enums.PaymentType;
import com.atguigu.ssyx.model.order.OrderInfo;
import com.atguigu.ssyx.model.order.PaymentInfo;
import com.atguigu.ssyx.pay.mapper.PaymentInfoMapper;
import com.atguigu.ssyx.pay.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {

    private final PaymentInfoMapper paymentInfoMapper;
    private final OrderFeignClient orderFeignClient;
    private final RabbitService rabbitService;


    //3.1 支付成功，修改支付记录表状态：已经支付
    //3.2 支付成功，修改订单记录已经支付，库存扣减
    @Override
    public void paySuccess(String orderNo, Map<String, String> resultMap) {
        //1 查询当前订单支付记录表状态是否是已经支付
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        if (paymentInfo.getPaymentStatus() != PaymentStatus.UNPAID) {
            return;
        }

        //2 如果支付记录表支付状态没有支付，更新
        paymentInfo.setPaymentStatus(PaymentStatus.PAID);
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackContent(resultMap.toString());
        baseMapper.updateById(paymentInfo);

        //3 整合RabbitMQ实现 修改订单记录已经支付，库存扣减
        log.info("支付成功，发送消息到MQ:{}", orderNo);
        rabbitService.sendMessage(MqConst.EXCHANGE_PAY_DIRECT,// 交换机
                MqConst.ROUTING_MINUS_STOCK, orderNo);// 路由键, 订单编号
    }


    //根据orderNo查询支付记录
    @Override
    public PaymentInfo getPaymentInfoByOrderNo(String orderNo) {
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOrderNo, orderNo);
        return paymentInfoMapper.selectOne(wrapper);
    }


    //添加支付记录
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        PaymentInfo paymentInfo = new PaymentInfo();
        //远程调用service-order，根据orderNo查询订单信息 order_info
        OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(orderNo);
        if (orderInfo == null) {
            throw new SsyxException(ResultCodeEnum.DATA_ERROR);
        }
        BeanUtil.copyProperties(orderInfo, paymentInfo);
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(PaymentType.WEIXIN);//微信支付
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID);//正在支付
        String subject = "userId:" + orderInfo.getUserId() + "下订单";
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(new BigDecimal("0.01"));
        paymentInfoMapper.insert(paymentInfo);
        return paymentInfo;

    }
}
